import axios from "axios";
import type { AxiosInstance } from "axios";
import type { BBRequestConfig, BBRequestInterceptors } from "./type";
import { ElLoading, ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-loading.css";
import { LoadingInstance } from "element-plus/lib/components/loading/src/loading.js";

const DEFAULT_LOADING = true;

class BBRequest {
  instance: AxiosInstance;
  interceptors?: BBRequestInterceptors;
  loading?: LoadingInstance;
  showLoading?: boolean;

  constructor(config: BBRequestConfig) {
    this.instance = axios.create(config);
    this.showLoading = config.showLoading ?? DEFAULT_LOADING;
    this.interceptors = config.interceptors;
    //从config中取出的拦截器是实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptor
    );

    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );

    //添加所有实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: "正在请求数据...",
            background: "rgba(0,0,0,0.5)",
          });
        }
        return config;
      },
      (err) => {
        return err;
      }
    );
    this.instance.interceptors.response.use(
      (res) => {
        //将loading移出
        this.loading?.close();
        const data = res.data;
        if (data.returnCode === "-1001") {
          // console.log('请求失败，错误信息')
          ElMessage.error("操作失败");
        } else {
          return data;
        }
      },
      (err) => {
        //将loading移出
        this.loading?.close();
        //判断不同的 HttpErrorCode显示不同的错误信息
        if (err.response.status === 404) {
          console.log("错误信息");
          ElMessage.error("出错了");
        }
        return err;
      }
    );
  }

  request<T>(config: BBRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config);
      }
      if (config.showLoading === false) {
        this.showLoading = false;
      } else if (config.showLoading === true) {
        this.showLoading = true;
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res);
          }
          //将showloading设置true，这样不会影响下一个请求
          this.showLoading = DEFAULT_LOADING;

          //将结果resolve返回出去
          resolve(res);
        })
        .catch((err) => {
          //将showloading设置true，这样不会影响下一个请求
          this.showLoading = DEFAULT_LOADING;
          reject(err);
          return err;
        });
    });
  }

  get<T = any>(config: BBRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "GET" });
  }

  post<T = any>(config: BBRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "POST" });
  }

  delete<T = any>(config: BBRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "DELETE" });
  }

  patch<T = any>(config: BBRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "PATCH" });
  }
}

export default BBRequest;
